﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 说明，所有接口用[HttpPost]，所有数据返回以Result为基础；
    /// 如需返回数据，则使用泛型Result<T>；
    /// 如返回仅为bool，则直接用Status字段控制（默认为false）；
    /// 如需错误提示，用Message；
    /// 如有约定返回，用StatusCode。
    /// </summary>
    public class BaseApiController : ApiController
    {
        protected readonly string CatrdId = ConfigurationManager.AppSettings["CardId"];
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(BaseApiController));
        protected int FailScanTime = Convert.ToInt32(ConfigurationManager.AppSettings["FailScanTime"]);
        protected int VariableQrEachOneTimes = Convert.ToInt32(ConfigurationManager.AppSettings["VariableQrEachOneTimes"]);//可变二维码每人抽奖次数
        protected string ApiUrl = ConfigurationManager.AppSettings["ApiUrl"];
        protected int MsgExpireTime = Convert.ToInt32(ConfigurationManager.AppSettings["MsgExpireTime"]);
        protected SysConfig SysConfig;
        protected readonly MatrixCloudCenterInterFuncBll MatrixCloudCenterInterFuncBllObj = new MatrixCloudCenterInterFuncBll();
        protected int FixedCouponShopId = Convert.ToInt32(ConfigurationManager.AppSettings["FixedCouponShopId"]);//固定发劵店铺
        protected int PageSize = 10;
        protected string MkysMcId = ConfigurationManager.AppSettings["MkysMcId"];
        
        /// <summary>
        /// 检查接口调用权限
        /// </summary>
        /// <returns></returns>
        protected Result<string> CheckPermission(string interfaceEntryName)
        {
            var strClientIp = IpHelper.IPAddress;
            _fileLog.Info("BaseApiController | " + interfaceEntryName + " | Client Ip: " + strClientIp +
                          " | Called time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            var strLimitIpSwitch = ConfigurationManager.AppSettings["LimitIpSwitch"];
            if (strLimitIpSwitch == "0")
            {
                return new Result<string>
                {
                    Status = true,
                    Message = "No limited Ip",
                    Data = strClientIp
                };
            }
            var strAccessIp = ConfigurationManager.AppSettings["AccessIp"];
            if (string.IsNullOrWhiteSpace(strAccessIp))
            {
                return new Result<string>
                {
                    Status = true,
                    Message = "No limited Ip",
                    Data = strClientIp
                };
            }
            var arAccessIp = strAccessIp.Split(',');
            var bCheck = arAccessIp.Any(accessIp => strClientIp == accessIp);

            if (!bCheck)
            {
                _fileLog.Error("BaseApiController | " + interfaceEntryName + " | Error: Invalid Ip - " + strClientIp);
            }
            return new Result<string>
            {
                Status = bCheck,
                Message = bCheck ? "Access successfully. " : "Invalid Ip - " + strClientIp,
                Data = strClientIp
            };
        }

        /// <summary>
        /// 系统配置
        /// </summary>
        public BaseApiController()
        {
            SysConfig = SysConfigBLL.Instance.GetModelList().FirstOrDefault();
        }

        /// <summary>
        /// 获取公众号信息
        /// </summary>
        /// <param name="projectInfo"></param>
        /// <returns></returns>
        protected MxApiWechatInfo GetWeChatInfoByMcId(MatrixCloudProjectInfo projectInfo)
        {
            var resultWechatInfo = MatrixCloudCenterInterFuncBllObj.GetWechatInfo(projectInfo.PjMcId,
                projectInfo.PjSecret);

            if (!resultWechatInfo.Status || resultWechatInfo.Data == null ||
                string.IsNullOrEmpty(resultWechatInfo.Data.AppId) ||
                string.IsNullOrWhiteSpace(resultWechatInfo.Data.Secret))
            {
                _fileLog.Error(
                    "BaseApiController | GetWeChatInfoByMcId | Cannot get WechatMp Info from Matrix-Cloud-Center - " +
                    projectInfo.PjMcId);
                throw new Exception("Cannot get the WeChat info of the project McId - " + projectInfo.PjMcId);
            }
            return resultWechatInfo.Data;
        }

        /// <summary>
        /// 图片get
        /// </summary>
        /// <param name="imgUrl"></param>
        /// <param name="type">_b (大)_s(中) _m(小) </param>
        /// <returns></returns>
        public static string Image(string imgUrl, string type)
        {
            if (string.IsNullOrEmpty(imgUrl))
            {
                return "";
            }
            string imgAddress;
            string[] imgeUrlTrr = imgUrl.Split('.');
            if (imgeUrlTrr.Length < 2)
            {
                imgAddress = imgUrl;
            }
            switch (type)
            {
                case "b":
                    imgAddress = imgeUrlTrr[0] + "_b." + imgeUrlTrr[1];
                    break;
                case "s":
                    imgAddress = imgeUrlTrr[0] + "_s." + imgeUrlTrr[1];
                    break;
                case "m":
                    imgAddress = imgeUrlTrr[0] + "_m." + imgeUrlTrr[1];
                    break;
                default:
                    imgAddress = imgUrl;
                    break;
            }
            return imgAddress;
        }

        /// <summary>
        /// 获取当前接口当前云迈云项目资料
        /// </summary>
        /// <param name="mcId"></param>
        /// <returns></returns>
        public MatrixCloudProjectInfo GetCurrentMatrixCloudProjectInfo(string mcId)
        {
            var localProjectInfo = MatrixCloudProjectInfoBLL.Instance.GetModelByPjMcId(mcId);
            if (localProjectInfo == null || localProjectInfo.Id == 0 ||
                string.IsNullOrWhiteSpace(localProjectInfo.PjMcId))
            {
                return null;
            }
            var checkResult =
                    MatrixCloudCenterInterFuncBllObj.CheckAndGetMatrixCloudProjectInfo(localProjectInfo.PjCode);
            return checkResult.Status ? checkResult.Data : null;
        }

        /// <summary>
        /// 通过openid获取用户信息
        /// </summary>
        public MxApiWechatUser GetMxApiWechatUserInfo(string openId, string mcId)
        {
            var projectInfo = GetCurrentMatrixCloudProjectInfo(mcId);
            if (projectInfo == null || projectInfo.Id == 0 || string.IsNullOrWhiteSpace(projectInfo.PjMcId) ||
                string.IsNullOrWhiteSpace(projectInfo.PjSecret))
            {
                _fileLog.Error("BaseApiController | GetMxApiWechatUserInfo | Error: Invalid McId.");
                return null;
            }
            var resultWechatUser = MatrixCloudCenterInterFuncBllObj.GetWechatUserInfo(openId, projectInfo.PjMcId,
                    projectInfo.PjSecret);
            if (!resultWechatUser.Status || resultWechatUser.Data == null)
            {
                _fileLog.Error("BaseApiController | GetMxApiWechatUserInfo | Cannot get the wechat user info." +
                               resultWechatUser.Message);
                return null;
            }
            return resultWechatUser.Data;
        }
        
        /// <summary>
        ///根据uinionId 获取用户信息
        /// </summary>
        public MxApiWechatUser GetMxApiWechatUserInfoByuinionId(string uinionId, string mcId)
        {
            var projectInfo = GetCurrentMatrixCloudProjectInfo(mcId);
            if (projectInfo == null || projectInfo.Id == 0 || string.IsNullOrWhiteSpace(projectInfo.PjMcId) ||
                string.IsNullOrWhiteSpace(projectInfo.PjSecret))
            {
                _fileLog.Error("BaseApiController | GetMxApiWechatUserInfo | Error: Invalid McId.");
                return null;
            }
            var resultWechatUser = MatrixCloudCenterInterFuncBllObj.GetWechatUserInfoByUnionId(uinionId, projectInfo.PjMcId,
                    projectInfo.PjSecret);
            if (!resultWechatUser.Status || resultWechatUser.Data == null)
            {
                _fileLog.Error("BaseApiController | GetMxApiWechatUserInfo | Cannot get the wechat user info." +
                               resultWechatUser.Message);
                return null;
            }
            return resultWechatUser.Data;
        }
    }
}
